import bpy
from bpy.types import Panel
from ...addon.naming import FluidLabNaming
from ...addon.paths import FluidLabPreferences
from ..ui_module_panel import FLUIDLAB_ModulePanel
# from ...addon.preferences import FluidLabAddonPreferences
from ...libs.functions.get_common_vars import get_common_vars
from ...libs.functions.nodes import get_node_index_or_identifier_by
from ...libs.functions.common_ui_elements import title_header, collapsable, special_ui_element



class FLUIDLAB_PT_rendering_ui(Panel, FLUIDLAB_ModulePanel):
    fluidlab_section = 'RENDERING'
    bl_idname = "FLUIDLAB_PT_rendering_ui"
    bl_label = "Module"

    def draw(self, context):

        scn, rendering_props, ui, toggles = get_common_vars(context, get_scn=True, get_rendering=True, get_ui=True, get_toggles=True)
        cycles = scn.cycles

        layout = self.layout
        layout.use_property_split = True
        layout.use_property_decorate = False

        col = layout.column(align=True)
        title_header(col, "Rendering")

        main_col = col.box().column(align=True)
        main_col.use_property_split = True
        main_col.use_property_decorate = False

        if ui.ui_mode == 'BASIC':
        
            # ------------- #
            """ UI BASICA """
            # ------------- #
        
            main_col.label(text="Hola Mundo Basico")

    
        elif ui.ui_mode == 'ADVANCED':
        
            # --------------- #
            """ UI AVANZADA """
            # --------------- # 

            subsections_header = main_col.row(align=True)
            subsections_header.use_property_split = False
            subsections_header.scale_y = 1.3
            subsections_header.prop(ui, "rendering_subsections", expand=True)
            main_col.separator()

            file_format = scn.render.image_settings.file_format
            format = scn.render.ffmpeg.format
            constant_rate_factor = scn.render.ffmpeg.constant_rate_factor

            if ui.rendering_subsections == 'VIEWPORT':
                
                #########################
                """ Viewport section """
                #########################
                
                viewport_settings = collapsable(
                    main_col,
                    toggles,
                    "rendering_viewport_settings",
                    "Viewport Settings",
                    'VIEW_PERSPECTIVE',
                    align=True,
                )
                if viewport_settings:

                    pv = viewport_settings.row(align=True)
                    pv.scale_y = 1.3
                    pv.operator("fluidlab.pretty_viewport", text="Pretty Viewport", depress=rendering_props.viewport_switched)

                    viewport_settings.separator()
                    cr = context.scene.render
                    res_col = viewport_settings.column(align=True)
                    partout = viewport_settings.column(align=True)
                    res_col.use_property_split = False

                    flip_row = res_col.row(align=True)
                    flip_row.prop(cr, "resolution_x", text="")
                    flip_row.prop(cr, "resolution_y", text="")

                    fstart_fend_row = res_col.row(align=True)
                    fstart_fend_row.prop(scn, "frame_start", text="Frame Start")
                    fstart_fend_row.prop(scn, "frame_end", text="End")

                    res_row = res_col.row(align=True)
                    res_row.prop(rendering_props, "bt_percentages", expand=True)

                    if scn.camera:
                        cam = scn.camera.data
                        if cam:
                            partout.separator()
                            col = partout.column(align=False, heading="Passepartout")
                            col.use_property_decorate = False
                            row = col.row(align=True)
                            sub = row.row(align=True)
                            sub.prop(cam, "show_passepartout", text="")
                            sub = sub.row(align=True)
                            sub.active = cam.show_passepartout
                            sub.prop(cam, "passepartout_alpha", text="")
                            row.prop_decorator(cam, "passepartout_alpha")

                    # res_row = res_col.row(align=True)
                    # res_row.prop(cr, "resolution_percentage", text="")
                    r_bts = res_col.row(align=True)
                    r_bts.scale_y = 1.3
                    
                    fbook = r_bts.row(align=True)

                    addon_preferences = FluidLabPreferences.get_prefs(context)
                    flipbooks_path = addon_preferences.flipbooks_path
                    if len(flipbooks_path) == 0:
                        res_col.separator()
                        res_col.prop(addon_preferences, "flipbooks_path", text="Flipbook Path")
                        fbook.enabled = False

                    fbook.operator("fluidlab.flipbook", icon='RENDER_ANIMATION', text="FlipBook")
                    r_bts.operator("render.play_rendered_anim", icon='RENDER_STILL', text="View Render")

                    viewport_settings.separator()
                    

                    # image_settings = cr.image_settings
                    # viewport_settings.template_image_settings(image_settings, color_management=False)

                    # if image_settings.file_format in {'FFMPEG', 'XVID', 'H264', 'THEORA'}:
                    #     viewport_settings.separator()
                    #     viewport_settings.alignment = 'RIGHT'
                    #     viewport_settings.use_property_split = False
                    #     viewport_settings.prop(cr.ffmpeg, "format")

                    vs_row = viewport_settings.row(align=True)
                    vs_row.use_property_split = True
                    
                    if file_format != 'FFMPEG' or format != 'MPEG4' or constant_rate_factor != 'PERC_LOSSLESS':
                        quick_mp4 = vs_row.row(align=True)
                        quick_mp4.scale_x = 0.6
                        quick_mp4.operator("fluidlab.quick_mp4", text="MP4")
                    else:
                        vs_row.label(text="")
                    
                    # version simplificada:
                    vs_row.prop(rendering_props, "file_format")
                    if rendering_props.file_format in {'FFMPEG', 'XVID', 'H264', 'THEORA'}:
                        viewport_settings.prop(rendering_props, "container")
                

                main_col.separator()
                material_display = collapsable(
                    main_col,
                    toggles,
                    "rendering_viewport_display",
                    "Viewport Display",
                    'SHADING_WIRE',
                    align=True,
                )
                if material_display:
                    material_display.use_property_split = False
                    
                    display = context.scene.display
                    shading = context.space_data.shading

                    # Shadows:
                    shadow = material_display.column(align=True)
                    shadow.scale_y = 1.3
                    shadow.prop(shading, "show_shadows", toggle=True)
                    shadow_options = material_display.column(align=True)

                    if shading.show_shadows:
                        shadow_options.prop(display, "light_direction", text="")
                        shadow_options.prop(shading, "shadow_intensity")
                        shift_focus = shadow_options.row(align=True)
                        shift_focus.prop(display,"shadow_shift", text="Shift")
                        shift_focus.prop(display,"shadow_focus", text="Focus")
                    
                    material_display.separator()

                    # Cavity:
                    cavity = material_display.column(align=True)
                    cavity.scale_y = 1.3
                    cavity.prop(shading, "show_cavity", toggle=True)
                    
                    if shading.show_cavity:
                        flow = material_display.grid_flow(row_major=True, even_columns=True, even_rows=True, align=True, columns=2)
                        flow.prop(shading, "cavity_ridge_factor")
                        flow.prop(shading, "cavity_valley_factor")
                        flow.prop(shading, "curvature_ridge_factor")
                        flow.prop(shading, "curvature_valley_factor")

                        col = material_display.column(align=True)
                        col.prop(display, "matcap_ssao_samples")
                        col.prop(display, "matcap_ssao_distance")
                        col.prop(display, "matcap_ssao_attenuation")

                
                ob = context.object
                if ob.type == 'MESH':
                    mat = ob.active_material
                    if mat:
                        
                        main_col.separator()
                        material_display = collapsable(
                            main_col,
                            toggles,
                            "rendering_material_display",
                            "Material Display",
                            'NODE_MATERIAL',
                            align=True,
                        )
                        if material_display:
                            material_display.prop(mat, "diffuse_color", text="Color")
                            material_display.prop(mat, "metallic")
                            material_display.prop(mat, "roughness")

            elif ui.rendering_subsections == 'RENDER':

                #########################
                """ Rendering section """
                #########################

                bt_switcher_eevee = {
                    "type": "operator",
                    "from": None,
                    "prop": "fluidlab.switcher_engine_eevee",
                    "text": "Eevee",
                    "toggle": True,
                    "icon": None,
                    "depress": scn.render.engine == 'BLENDER_EEVEE',
                }

                bt_switcher_cycles = {
                    "type": "operator",
                    "from": None,
                    "prop": "fluidlab.switcher_engine_cycles",
                    "text": "Cycles",
                    "toggle": True,
                    "icon": None,
                    "depress": scn.render.engine == 'CYCLES',
                }

                rendering_settings = collapsable(
                    main_col,
                    toggles,
                    "rendering_settings",
                    "Render Settings",
                    'RESTRICT_RENDER_OFF',
                    align=True,
                    button_settings1=bt_switcher_eevee,
                    button_settings2=bt_switcher_cycles
                )
                if rendering_settings:
                    
                    cr = context.scene.render
                    res_col = rendering_settings.column(align=True)
                    res_col.use_property_split = False

                    flip_row = res_col.row(align=True)
                    flip_row.prop(cr, "resolution_x", text="")
                    flip_row.prop(cr, "resolution_y", text="")

                    fstart_fend_row = res_col.row(align=True)
                    fstart_fend_row.prop(scn, "frame_start", text="Frame Start")
                    fstart_fend_row.prop(scn, "frame_end", text="End")

                    if scn.render.engine == 'CYCLES':
                        res_col.prop(cycles, "time_limit")

                    res_row = res_col.row(align=True)
                    res_row.prop(cr, "resolution_percentage", text="")
                    # res_col.separator()

                    r_bts = res_col.row(align=True)
                    r_bts.scale_y = 1.3
                    r_bts.operator("render.render", icon='RESTRICT_RENDER_OFF', text="Render").animation = True
                    r_bts.operator("render.play_rendered_anim", icon='RENDER_STILL', text="View Render")
                    
                    rendering_settings.separator()
                    rendering_settings.prop(cr, "filepath", text="")

                    rendering_settings.separator()
                    image_settings = cr.image_settings

                    # Quick MP4:
                    flow = rendering_settings.grid_flow(row_major=True, even_columns=False, even_rows=False, align=True, columns=2)
                    left = flow.column(align=True)
                    if file_format != 'FFMPEG' or format != 'MPEG4' or constant_rate_factor != 'PERC_LOSSLESS':
                        left.operator("fluidlab.quick_mp4", text="MP4")
                    else:
                        left.label(text="")

                    # File Format:
                    right = flow.column(align=True)
                    right.template_image_settings(image_settings, color_management=False)

                    if image_settings.file_format in {'FFMPEG', 'XVID', 'H264', 'THEORA'}:
                        rendering_settings.separator()
                        rendering_settings.alignment = 'RIGHT'
                        rendering_settings.use_property_split = False
                        rendering_settings.prop(cr.ffmpeg, "format")

                        ffmpeg = context.scene.render.ffmpeg
                        if ffmpeg:
                            needs_codec = ffmpeg.format in {'AVI', 'QUICKTIME', 'MKV', 'OGG', 'MPEG4', 'WEBM'}
                            if needs_codec:
                                rendering_settings.prop(ffmpeg, "codec")

                            use_crf = needs_codec and ffmpeg.codec in {'H264', 'MPEG4', 'WEBM', 'AV1'}
                            if use_crf:
                                rendering_settings.prop(ffmpeg, "constant_rate_factor")

                    rendering_settings.separator()
                    
                    rendering_settings.use_property_split = False

                    if scn.render.engine == 'CYCLES':
                        rendering_settings.prop(cycles, "use_denoising", text="Denoise", toggle=True)
                    rendering_settings.prop(cr, "film_transparent", text="Film Transparent", toggle=True)
                
            elif ui.rendering_subsections == 'WORLD':
                
                #####################
                """ World section """
                #####################
                worlds = bpy.data.worlds
                
                world_settings = collapsable(
                    main_col,
                    toggles,
                    "rendering_world_settings",
                    "World Settings",
                    'WORLD',
                    align=True,
                )
                if world_settings:

                    if FluidLabNaming.WORLD not in worlds:

                        bt_aw = world_settings.row(align=True)
                        bt_aw.scale_y = 1.3
                        bt_aw.operator("fluidlab.world_add", text="Add FluidLab World")

                    else:

                        bt_rw = world_settings.row(align=True)
                        bt_rw.scale_y = 1.3
                        bt_rw.alert = True
                        bt_rw.operator("vdblab.world_rm", text="Remove FluidLab World", icon='TRASH')

                        world_settings.separator()

                        world = worlds.get(FluidLabNaming.WORLD)
                        if world:

                            node_mix_color = world.node_tree.nodes.get(FluidLabNaming.WORLD_MIX)
                            if node_mix_color:

                                world_settings.prop(node_mix_color, "mute", text="Show Texture")
                                
                                if not node_mix_color.mute:

                                    node_mix_input = get_node_index_or_identifier_by("index", "name", "inputs", node_mix_color, "B", False)
                                    if node_mix_input:
                                        world_settings.prop(node_mix_color.inputs[node_mix_input], "default_value", text="Color")

                                bg_node = world.node_tree.nodes.get(FluidLabNaming.WORLD_BACKGROUND)
                                node_bg_input = get_node_index_or_identifier_by("identifier", "name", "inputs", bg_node, "Strength", False)
                                if node_bg_input:
                                    world_settings.prop(bg_node.inputs[node_bg_input], "default_value", text="Strength")

                                world_settings.separator()

                                hdr_options = collapsable(
                                    world_settings,
                                    toggles,
                                    "hdr_img_collapsable",
                                    "HDR World",
                                    'IMAGE_BACKGROUND',
                                    align=False,
                                )
                                if hdr_options:
                                    special_ui_element(context, hdr_options, world, [FluidLabNaming.WORLD_ENV_TEXT])